<template>
	<view class="uni-tab-bar">
		<scroll-view scroll-y class="list scroll-height" @scrolltolower="loadmore">
			<template v-if="item.list.length > 0">
				<block v-for="(item1, index1) in item.list" :key="index1">
					<index-list :item="item1" :index="index1" :disabled="isSelectStaff && item1.type == 'department'" @opendetail="opendetail"
					 @checkboxChange="checkboxChange"></index-list>
				</block>
				<load-more :loadtext="item.loadtext" @clickLoadMore="clickLoadMore"></load-more>
			</template>
			<template v-else-if="!item.firstload">
				<view style="
            font-size: 50upx;
            font-weight: bold;
            color: #cccccc;
            padding-top: 100upx;
          "
				 class="u-f-ajc">Loading ...</view>
			</template>
			<template v-else>
				<no-thing></no-thing>
			</template>
		</scroll-view>
		<view class="footer-btn">
			<view class="selected-user-wrapper">
				<view class="selected-title">已选：</view>
				<template v-if="selectedStaff.length > 0">
					<scroll-view class="scroll-view_H" scroll-x="true">
						<block v-for="(item, index) in selectedStaff" :key="index">
							<view class="scroll-view-item_H" @tap="removeSelectedStaff(item, index)">
								<text class="staff-name">{{ item.userName }}</text>
								<image class="staff-remove" src="../../static/remove.png"></image>
							</view>
						</block>
					</scroll-view>
				</template>
			</view>
			<view class="to-confirm" @tap="toConfirm()">确定</view>
		</view>
	</view>
</template>

<script>
	import loadMore from '../../components/common/load-more';
	import noThing from '../../components/common/no-thing';
	import indexList from '../../components/authority/indexList';
	import {
		listByDeptid,
		getDeptsByParentId,
		getAddPower,
	} from '../../common/service.js';
	export default {
		components: {
			loadMore,
			noThing,
			indexList,
		},
		data() {
			return {
				loginInfo: {},
				parentId: '',
				deptId: '',
				isSelectStaff: false,
				isJump: false, // true 自身跳转，false 从外部页面进来
				selectedStaff: [],
				item: {
					loadtext: '上拉加载更多',
					list: [],
					page: 1,
					firstload: false,
				},
			};
		},
		onLoad(e) {
			// 登录用户信息
			if (e.loginInfo) {
				this.loginInfo = JSON.parse(e.loginInfo);
			}

			// 部门id，用于上拉加载
			if (e.deptId) {
				this.deptId = JSON.parse(e.deptId);
			}

			// 是否内部跳转，选择下级部门或人员时，值为true
			if (e.isJump) {
				this.isJump = JSON.parse(e.isJump);
			}

			// 是否只选择员工,传true不能选部门，只能选员工
			if (e.isSelectStaff) {
				this.isSelectStaff = JSON.parse(e.isSelectStaff);
			}

			// 设置导航栏标题
			if (e.title) {
				uni.setNavigationBarTitle({
					title: JSON.parse(e.title),
				});
			}

			// 上页传送过来的所有数据
			if (e.postStaff) {
				const postStaff = JSON.parse(e.postStaff);
				if (this.isJump) {
					if (postStaff.length <= 0) {
						this.item.firstload = true;
						this.item.loadtext = '没有更多数据了';
					}
					this.item.list = postStaff;
					const value = uni.getStorageSync('checked_staff');
					if (value) {
						// 展示顶部已选数据
						this.selectedStaff = value;
					}
				} else {
					if (this.loginInfo.parentUserId && this.loginInfo.powerModule) {
						this.initial(this.loginInfo, postStaff);
					}
				}
			}
		},
		onShow: function() {
			const value = uni.getStorageSync('checked_staff');
			if (value && this.isJump) {
				this.selectedStaff = value;

				this.checkItem();
			}
		},
		methods: {
			initial: function(logInfo, postStaff) {
				getAddPower({
						parentUserId: logInfo.parentUserId,
						powerModule: logInfo.powerModule,
					},
					(res) => {
						if (res && res.data && res.data.code == 200) {
							this.item.firstload = true;
							this.item.loadtext = '没有更多数据了';
							if (res.data.data) {
								let list = res.data.data;
								let arr = [];
								if (list.length > 0) {
									for (let i = 0; i < list.length; i++) {
										arr = arr.concat(this.__formatPower(list[i]));
									}
								}
								this.item.list = arr;

								const selectedItem = postStaff.filter((item) => item.checked);
								// 展示顶部已选数据
								this.selectedStaff = selectedItem;
								// 清空缓存
								uni.removeStorageSync('checked_staff');
								uni.clearStorage();

								this.checkItem();
								// 保存
								uni.setStorageSync('checked_staff', selectedItem);
							}
						} else {
							uni.showToast({
								title: '查询权限失败',
								duration: 2000,
							});
						}
					},
					(err) => {
						uni.showToast({
							title: '查询权限失败',
							duration: 2000,
						});
					}
				);
			},
			// 格式转化
			__formatPower(item) {
				let arr = [];

				if (item.toSysDepts && item.toSysDepts.length) {
					item.toSysDepts.forEach((dept) => {
						arr.push({
							userId: dept.deptId.toString(),
							userImage: '../../static/dept.png',
							userName: dept.deptName,
							type: 'department',
							checked: false,
							nickName: item.nickName,
						});
					});
				} else if (item.toSysUsers && item.toSysUsers.length) {
					item.toSysUsers.forEach((user) => {
						arr.push({
							userId: user.userName.toString(),
							userImage: user.avatar,
							userName: user.nickName,
							type: 'employee',
							checked: false,
							nickName: item.nickName,
						});
					});
				}

				return arr;
			},
			checkboxChange: function(e) {
				const [item, index] = e;

				const values = [];
				this.selectedStaff.map((s) => {
					values.push(s.userId);
				});
				if (values.includes(item.userId)) {
					if (!item.checked) {
						let staffIndex = this.selectedStaff.findIndex(
							(staff) => staff.userId === item.userId
						);
						if (staffIndex != -1) {
							this.selectedStaff.splice(staffIndex, 1);
						}
					}
				} else {
					if (item.checked) {
						this.selectedStaff.push(item);
					}
				}
				
				// 保存
				uni.setStorageSync('checked_staff', this.selectedStaff);
			},
			removeSelectedStaff(item, index) {
				this.selectedStaff.splice(index, 1);

				let staffIndex = this.item.list.findIndex(
					(staff) => staff.userId == item.userId
				);
				if (staffIndex != -1) {
					this.item.list[staffIndex].checked = false;
				}
			},
			opendetail(e) {
				const [item, index] = e;
				// 员工已是最后一级
				if (item.type == 'employee') {
					return;
				}
				uni.setStorageSync('checked_staff', this.selectedStaff);

				// 部门下: 子部门和人员都要查
				this.parentId = item.userId;
				this.deptId = item.userId;
				this.getDetailData(item);
			},
			/**
			 * 根据 id 进行数组去重
			 * @param {array} origin 原始数组
			 */
			unique(origin) {
				let temp = {};
				return origin
					.reverse()
					.filter((item) =>
						item.userId in temp ? false : (temp[item.userId] = true)
					);
			},
			getDetailData(currItem) {
				if (!this.parentId || !this.deptId) return;
				const params = {
					pageNum: 1,
					pageSize: Number.MAX_SAFE_INTEGER,
					parentId: this.parentId,
				};
				getDeptsByParentId(
					params,
					(res) => {
						let arr = [];
						let list = res.data.data;
						for (let i = 0; i < list.length; i++) {
							arr.push(this.__format(list[i]));
						}
						const params = {
							pageNum: this.item.page,
							pageSize: 50,
							deptId: this.deptId,
						};
						listByDeptid(
							params,
							(res) => {
								let list = res.data.rows;
								for (let i = 0; i < list.length; i++) {
									arr.push(this.__formatStaff(list[i]));
								}
								this.item.firstload = true;
								if (list.length < 50) {
									this.item.loadtext = '没有更多数据了';
								} else {
									this.item.loadtext = '上拉加载更多';
								}
								this.isJump = true;
								uni.navigateTo({
									url: '../../pages/selectStaff/selectStaff?isSelectStaff=' +
										JSON.stringify(this.isSelectStaff) +
										'&postStaff=' +
										JSON.stringify(arr) +
										'&title=' +
										JSON.stringify(currItem.userName) +
										'&isJump=' +
										JSON.stringify(this.isJump) +
										'&deptId=' +
										JSON.stringify(this.deptId) +
										'&loginInfo=' +
										JSON.stringify(this.loginInfo),
								});
							},
							(err) => {
								uni.showToast({
									title: `获取员工数据失败`,
									duration: 2000,
								});
							}
						);
					},
					(err) => {
						uni.showToast({
							title: `获取部门数据失败`,
							duration: 2000,
						});
					}
				);
			},
			// 格式转化
			__format(item) {
				return {
					userId: item.deptId.toString(),
					userImage: '../../static/dept.png',
					userName: item.deptName,
					type: 'department',
					checked: false,
				};
			},
			// 格式转化
			__formatStaff(item) {
				return {
					userId: item.userName,
					userImage: item.thumbAvatar,
					userName: item.nickName,
					type: 'employee',
					checked: false,
				};
			},
			// 上拉加载
			loadmore() {
				if (this.item.loadtext != '上拉加载更多') {
					return;
				}
				if (this.deptId) {
					// 部门ID，为了解决获取用户列表加载更多需求
					// 修改状态
					this.item.loadtext = '加载中...';
					this.item.page++;
					const params = {
						pageNum: this.item.page,
						pageSize: 50,
						deptId: this.deptId,
					};
					listByDeptid(
						params,
						(res) => {
							let list = res.data.rows;
							let arr = [];
							for (let i = 0; i < list.length; i++) {
								arr.push(this.__formatStaff(list[i]));
							}
							this.item.firstload = true;
							if (list.length < 50) {
								this.item.loadtext = '没有更多数据了';
							} else {
								this.item.loadtext = '上拉加载更多';
							}
							this.item.list = this.item.list.concat(arr);
							this.checkItem();
						},
						(err) => {
							uni.showToast({
								title: `获取员工数据失败`,
								duration: 2000,
							});
						}
					);
				}
			},
			clickLoadMore(e) {
				this.item.loadtext = e.detail.loadtext;
				this.loadmore();
			},
			toConfirm() {
				let callbackItems = this.selectedStaff.slice();
				if (callbackItems.length <= 0) {
					uni.showToast({
						title: '请选择至少一项',
					});
					return;
				}
				var pages = getCurrentPages(); // 获取栈实例
				let perPage = pages[0];
				pages.forEach((page) => {
					if (
						this.isSelectStaff &&
						page.hasOwnProperty('callbackStaff') &&
						page.hasOwnProperty('loginInfo')
					) {
						page['callbackStaff'] = this.unique(callbackItems);
						page['loginInfo'] = page.loginInfo;

						perPage = page;
						const index = pages.findIndex((x) => x._uid === perPage._uid);
						this.back(pages.length - index - 1)

						return;
					} else if (
						!this.isSelectStaff &&
						page.hasOwnProperty('callbackItems') &&
						page.hasOwnProperty('loginInfo')
					) {
						page['callbackItems'] = this.unique(callbackItems);
						page['loginInfo'] = page.loginInfo;

						perPage = page;
						const index = pages.findIndex((x) => x._uid === perPage._uid);
						this.back(pages.length - index - 1)

						return;
					}
				});
			},
			checkItem() {
				let items = this.item.list;
				let values = [];
				this.selectedStaff.map((s) => {
					values.push(s.userId);
				});
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					const item = items[i];
					if (values.includes(item.userId)) {
						this.item.list[i].checked = true;
					} else {
						this.item.list[i].checked = false;
					}
				}
			},
			back(delta) {
				uni.navigateBack({
					delta: delta || 2
				});
			}
		},
	};
</script>

<style scoped>
	.scroll-height {
		margin-bottom: 269upx;
	}

	.footer-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: #ffffff;
		height: 269upx;
	}

	.to-confirm {
		margin: 30upx;
		margin-top: 60upx;
		width: calc(100% - 60upx);
		line-height: 100rpx;
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
		color: #ffffff;
		background: #3875c6;
		border-radius: 6upx;
	}

	.selected-user-wrapper {
		display: flex;
		align-items: center;
		margin: 30upx;
	}

	.staff-remove {
		width: 32upx;
		height: 32upx;
		vertical-align: middle;
		padding-left: 20upx;
	}

	.selected-title {
		display: inline-block;
		width: 110upx;
		font-size: 26upx;
		font-weight: 500;
		color: #333333;
	}

	.scroll-view_H {
		display: inline-block;
		white-space: nowrap;
		width: calc(100% - 110upx);
	}

	.scroll-view-item_H {
		margin-right: 20upx;
		padding: 0 18upx;
		display: inline-block;
		width: auto;
		height: 60upx;
		line-height: 60upx;
		background: #e8e8e8;
		border-radius: 4upx;
		text-align: center;
	}
</style>
